<template>
  <div class="chart" ref="chart" style="height: 100%"></div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'BarCharts',
  props: {
    data: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      chart: null
    }
  },
  watch: {
    data () {
      this.draw()
    }
  },
  methods: {
    draw () {
      this.chart.clear()
      const trafficWay = this.data
      const data = []
      const data1 = []
      const xdata = []
      for (var i = 0; i < trafficWay.length; i++) {
        xdata.push(trafficWay[i].name)
        data.push(
          {
            value: trafficWay[i].bm,
            name: trafficWay[i].name
          }
        )
        data1.push(
          {
            value: trafficWay[i].pm,
            name: trafficWay[i].name
          }
        )
      }
      const option = {
        grid: {
          left: 10,
          right: 10,
          bottom: 10,
          top: 30,
          containLabel: true
        },
        legend: {
          data: ['表面点', '剖面点']
        },
        xAxis: {
          type: 'category',
          splitLine: {
            show: false
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: true
          },
          axisLabel: {
            color: '#666',
            formatter: (a) => {
              let str = ''
              a.split('').forEach((item, index) => {
                if (index === 0) {
                  str += item
                } else {
                  str += '\n' + item
                }
              })
              return str
            }
          },
          data: xdata
        },
        yAxis: {
          type: 'value',
          name: '个',
          splitLine: {
            show: true
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#666'
          }
        },
        tooltip: {
          show: true,
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        dataZoom: {
          type: 'inside',
          start: 0,
          end: 40
        },
        series: [
          {
            name: '表面点',
            type: 'bar',
            barWidth: 10,
            data: data
          },
          {
            name: '剖面点',
            type: 'bar',
            barWidth: 10,
            data: data1
          }
        ]
      }

      this.chart.setOption(option)
    }
  },
  mounted () {
    this.chart = echarts.init(this.$refs.chart)
    // this.data.length && this.draw()
    this.draw()
  },
  beforeDestroy () {
    echarts.dispose(this.chart)
    this.chart = null
  }
}
</script>
